<?php

class ProductsActions extends Actions {

  public function pageDefault(){
    $this->authenticate();
    $this->redirect(Config::get('base_url', "/")."products/list");
  }

  public function pageList(){
    $this->authenticate();
    $csrf = Session::get('csrf');
    if(empty($csrf)) {
        $csrf = md5(rand(1, 1000) . microtime());
        Session::set('csrf', $csrf);
    }
    
    
    // $this->param('q') es un array con las condiciones de búsqueda (o null)
    // $this->param('b') es el parámetro que identifica a la búsqueda ya guardada en sesion (un nro de hasta 4 dígitos)
    
    if($this->param('q')){
      $busq = rand(1, 9999);
      $params = $this->param('q');
      Session::set('products_busqueda_'.$busq, $params);
      $this->redirect(Config::get('base_url').'products/list/b_'.$busq); 
    } else {
        $params = array();
        if($this->param('b')){
          $busq = $this->param('b');
          $params = Session::get('products_busqueda_'.$busq);
        }
    }
        
    
    
    $products = new Producto();
    
    $view = new View("listado");
    $options = array('page' => $this->param('page'));

    $where = array();
    $options['params'] = array();
    
    if(!$this->user->dataItem('editor')){
      $where[] = 'editor = :editor ';
      $options['params'] = array(':editor' => $this->user->dataItem('id'));
    }
    
    if(isset($params['q'])){
        $where[] = 'CONCAT(especies, laboratorio, nombre, descripcion, indicacion, indicacion2, principioactivo, detail1, detail2, detail3, detail4, paises) LIKE :query_string ';
        $options['params'][':query_string'] = '%'.$params['q'].'%';
    }

    if(!empty($params['a_pais'])){
        $where[] = 'paises LIKE :pais ';
        $options['params'][':pais'] = '%|'.$params['a_pais'].'|%';        
    }
    
    if(!empty($params['a_especie'])){
        $where[] = 'especies LIKE :especie ';
        $options['params'][':especie'] = '%|'.$params['a_especie'].'|%';
    }

    if(isset($params['a_estado']) && $params['a_estado'] != 'indistinto'){
        $where[] = 'status = :estado ';
        $options['params'][':estado'] = (int)(bool)$params['a_estado'];
    }

    if(isset($params['a_nombre'])){
        $where[] = 'nombre LIKE :nombre ';
        $options['params'][':nombre'] = '%'.$params['a_nombre'].'%';
    }
    
    if(isset($params['a_laboratorio'])){
        $where[] = 'laboratorio LIKE :laboratorio ';
        $options['params'][':laboratorio'] = '%'.$params['a_laboratorio'].'%';
    }
    
    
    
    //Inspect::view($params);
    
    $options['where'] = implode(' AND ', $where);
    
    if(empty($options['where'])) unset($options['where']);
    
    $view->data->products = $products->listPage($options);
    
    $lastPage = $products->lastPage($options);
    $page = max(min($lastPage, $this->param('page')), 1);
    $view->data->page = $page;
    $view->data->lastPage = $lastPage;
    $view->data->csrfToken = $csrf;
    $view->data->busq = empty($busq)?'':'/b_'.$busq;
    $view->data->params = $params;
    $view->data->mostrar_buscador_avanzado = isset($params['a_pais']) || isset($params['a_especie']) || isset($params['a_nombre']) || isset($params['a_estado']);
    $view->show();
  }
  
  public function pageCreate(){
    $this->authenticate();
    
    $error = array();
    $r = $this->param('r');
    $c = array();
    $paises = array();
    $especies = array();
    
    if(is_array($r)){
      if(empty($r['nombre'])) $error['nombre'] = "Indique un nombre.";
      
      
      if(!$this->user->dataItem('editor')){
        // Si no es un editor, forzamos el nombre del laboratorio
        $r['laboratorio'] = $this->user->dataItem('lab_name');
        $r['editor'] = $this->user->dataItem('id');
      };
      
      $c = $this->composicion(0, $this->param('c'));
      $paises = $this->param('p');
      $especies = $this->param('es');
      
      $image = $this->saveImage();
      if(!empty($image)) $r['imagen'] = $image;
      
      //trato de guardar el registro
      if(empty($error)){
        try {
          $p = Producto::create($r);
          
          if(is_null($paises)) $paises = array();
          if(is_null($especies)) $especies = array();
          
          $p->paises($paises)
                 ->especies($especies)
                 ->save();
          $d = $p->data();
          $id = $d['id'];
          $c = $this->composicion($id, $this->param('c'));  
          $p->composicion($c);

          $p = $this->param('page');
          $page = empty($p)?'':"/page_".$p;
          $b = $this->param('b');
          $busq = empty($b)?'':"/b_".$b;
          
          $this->redirect(Config::get('base_url', "/")."products/list".$busq.$page);
        } catch(Exception $e) {
          $error['_general'] = "No se pudo guardar el producto.";
        }
      }
    }

    $view = new View("crearEditar");
    $view->data->product = is_array($r)?$r:array();
    $view->data->error = $error;
    $view->data->composicion = $c;
    $view->data->paises = $paises;
    $view->data->especies = $especies;
    $view->data->creating = true;
    $view->data->showLab = $this->user->dataItem('editor');  // a los editores se les deja cambiar el lab
    $view->show();
    
  }

  public function pageEdit(){
    $this->authenticate();
    
    $error = array();
    $r = $this->param('r');
    if(!empty($r)) {
      foreach($r as $k => $v){
        $r[$k] = stripslashes($v);
      }
    }
    
    $this->userCanEdit($this->param('id'));
  

    if(is_array($r)){
      $this->userCanEdit($r['id']);
        //Inspect::view($r); die();
      if(empty($r['nombre'])) $error['nombre'] = "Indique un nombre.";
      
      if(!$this->user->dataItem('editor')){
        // Si no es un editor, forzamos el nombre del laboratorio
        $r['laboratorio'] = $this->user->dataItem('lab_name');
      };
      
      $image = $this->saveImage();
      if(!empty($image)) $r['imagen'] = $image;
      
      $c = $this->composicion($r['id'], $this->param('c'));
      
      $paises = $this->param('p');
      $paises = empty($paises)?array():$paises;
      
      $especies = $this->param('es');
      $especies = empty($especies)?array():$especies;
      
      //trato de guardar el registro
      if(empty($error)){
        try {
          $product = new Producto();
          $product->data($r)->paises($paises)->especies($especies)->save();
          $c = $this->composicion($r['id'], $this->param('c'));
          $product->composicion($c);
          
          $p = $this->param('page');
          $page = empty($p)?'':"/page_".$p;
          $b = $this->param('b');
          $busq = empty($b)?'':"/b_".$b;
          
          $this->redirect(Config::get('base_url', "/")."products/list".$busq.$page);
          
        } catch(Exception $e) {
          $error['_general'] = "No se pudo guardar el producto.";
        }
      }
    } else {
      $prod = Producto::find($this->param('id'));
      $r = $prod->data();
      $c = $prod->composicion();
      $paises = $prod->paises();
      $especies = $prod->especies();
    }

    $view = new View("crearEditar");
    $view->data->product = is_array($r)?$r:array();
    $view->data->error = $error;
    $view->data->composicion = $c;
    $view->data->paises = $paises;
    $view->data->especies = $especies;
    $view->data->creating = false;
    $view->data->showLab = $this->user->dataItem('editor');  // a los editores se les deja cambiar el lab
    $view->show();
  }
  
  public function pageDelete(){
    $this->authenticate();
    
    $csrf = Session::get('csrf');
    if($csrf != $this->param('token')) $this->redirect(Config::get('base_url', "/")."error/404");
    
    $products = new Producto();
    
    $products->delete(array('id' => $this->param("id")));
    
      $p = $this->param('page');
      $page = empty($p)?'':"/page_".$p;
      $b = $this->param('b');
      $busq = empty($b)?'':"/b_".$b;
      
      $this->redirect(Config::get('base_url', "/")."products/list".$busq.$page);
  }
  
  protected function composicion($prod_id, $c = array()){
    if(empty($c['producto'])) $c['producto'] = array();
    $o = array();
    $ord = 0;
    foreach($c['producto'] as $k => $prod){
      if(!empty($prod) || !empty($c['cantidad'][$k])) {
        $ord++;
        $o[] = array(
           'producto_id' => $prod_id,
           'titulo' => $prod,
           'descripcion' => $c['cantidad'][$k],
           'orden' => $ord
          ); 
      }
    }
    return $o;
  }
  
  protected function userCanEdit($prod_id){
    $product = Producto::find($prod_id)->data();
    $my_id = $this->user->dataItem('id');
    if($this->user->dataItem('editor') || $product['editor'] == $my_id){
        return true;
    } else {
        $this->redirect(Config::get('base_url', "/")."error/404");
    }
  }
  
  private function saveImage(){
        if(isset($_FILES) && isset($_FILES['imagen']) && !empty($_FILES['imagen']['name'])){
      $imagen =  isset($_FILES['imagen']['name'])?substr(md5(microtime(1)),0,6)."_".basename($_FILES['imagen']['name']):false;
      move_uploaded_file($_FILES['imagen']['tmp_name'], Config::get('public_path', '/').'/fotos/'.$imagen);
      return $imagen;
    }
    return '';
  }
  
}
